<template>
  <div class="cloze-page bg-f0f9f9">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link :to="`/english/weekTestExam?noticeId=${noticeId}&examPaperId=${examPaperId}`" @click.prevent="submitAnswers" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">完形填空</h5>
    </div>

    <!-- 文章内容 -->
    <div class="passage-container">
      <p v-html="processedPassage"></p>
    </div>

    <!-- 选项区域 -->
    <div class="options-container">
      <h6>Question {{ currentQuestionIndex + 1 }}</h6>
      <div
          v-for="(option) in currentQuestionOptions"
          :key="option.prefix"
          class="option-item"
          :class="{ selected: selectedAnswer === option.prefix }"
          @click="selectAnswer(currentQuestionIndex,option.prefix)"
      >
        {{ option.prefix }}. {{ option.content }}
      </div>
      <br/>
      <br/>
    </div>

    <!-- 导航按钮 -->
    <div class="navigation-buttons d-flex justify-content-between">
      <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary" @click="prevQuestion">上一题</button>
        <button class="btn btn-outline-secondary" @click="nextQuestion">下一题</button>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";
import {paperTypeDict, moduleTypeDict} from "@/router/dict"
import router from "@/router/index";
export default {
  name: 'ClozeView',
  data() {
    return {
      noticeId: null,
      examPaperId: null,
      questionId: null,
      selectedYear: null,
      passage: '',
      processedPassage: '',
      questions: [
        {
          item: []
        }
      ],
      currentQuestionIndex: 0,
      selectedAnswer: '',
      // 用于记录每道题选择的答案，以题目索引为键，选择的选项为值
      selectedOptions: {},
      // 新增，用于存储后端返回的完整数据（方便后续可能的拓展使用）
      backendData: {},
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      userAnswers: [], // 存储用户答案
    }
  },
  mounted() {
    this.examPaperId = this.$route.query.examPaperId;
    this.noticeId = this.$route.query.noticeId;
    this.fetchDataFromBackend();
    this.startTime = Date.now(); // 记录答题开始时间（毫秒数）
  },
  computed: {
    currentQuestionOptions() {
      return this.questions[this.currentQuestionIndex].item;
    }
  },
  methods: {
    async fetchDataFromBackend() {
      try {
        const moduleType = moduleTypeDict.find(item => item.code === 'wxtk').name;
        const params = {
          examPaperId: this.examPaperId,
          subjectName: 'english',
          moduleType: moduleType,
          currentQuestionIndex: 1
        }
        const response = await http.get('/student/question/getQuestionInfoForEnglish', {params: params});
        const data = response.data;
        if (data && data.code === 1 && data.response) {
          this.backendData = data.response;
          this.passage = data.response.article;
          this.examPaperId = data.response.examPaperId;
          this.questionId = data.response.questionId;
          // 处理文章内容，将下划线替换为带数字递增的 <span class="cloze-blank"> 标签
          this.processedPassage = this.replaceUnderlinesWithSpans(this.passage);
          this.questions = data.response.questions;
        } else {
          alert("暂无数据，请稍后再试");
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
        }
      } catch (error) {
        console.error('获取阅读数据失败:', error);
      }
    },
    replaceUnderlinesWithSpans(text) {
      let index = 1;
      let replacedText = text;
      while (replacedText.indexOf('________')!== -1) {
        replacedText = replacedText.replace('________', `<span class="cloze-blank" style="display: inline-block;min-width: 60px;border-bottom: 2px solid #40e0d0;text-align: center;margin: 0 5px;color: #40e0d0;">${index++}</span>`, 1);
      }
      return replacedText;
    },
    selectAnswer(index,key) {
      this.selectedAnswer = key;
      this.selectedOptions[this.currentQuestionIndex] = key;
      const existingIndex = this.userAnswers.findIndex(item => item.index === index);
      if(existingIndex > -1){
        this.userAnswers[existingIndex].value = key;
      }else{
        this.userAnswers.push({
          index: index === undefined? 0 : index,
          value: key
        })
      }
    },
    prevQuestion() {
      if (this.currentQuestionIndex > 0) {
        if (this.selectedAnswer) {
          this.selectedOptions[this.currentQuestionIndex] = this.selectedAnswer;
          const existingIndex = this.userAnswers.findIndex(item => item.index === this.currentQuestionIndex);
          if (existingIndex > -1) {
            this.userAnswers[existingIndex].value = this.selectedAnswer;
          } else {
            this.userAnswers.push({
              index: this.currentQuestionIndex,
              value: this.selectedAnswer
            });
          }
        }
        this.currentQuestionIndex--;
        this.selectedAnswer = this.selectedOptions[this.currentQuestionIndex] || '';
      }
    },
    nextQuestion() {
      if (this.currentQuestionIndex < this.questions.length - 1) {
        if (this.selectedAnswer) {
          this.selectedOptions[this.currentQuestionIndex] = this.selectedAnswer;
          const existingIndex = this.userAnswers.findIndex(item => item.index === this.currentQuestionIndex);
          if (existingIndex > -1) {
            this.userAnswers[existingIndex].value = this.selectedAnswer;
          } else {
            this.userAnswers.push({
              index: this.currentQuestionIndex,
              value: this.selectedAnswer
            });
          }
        }
        this.currentQuestionIndex++;
        this.selectedAnswer = this.selectedOptions[this.currentQuestionIndex] || '';
      }
    },
    async submitAnswers() {
      try {
        const currentTime = Date.now(); // 获取当前时间（毫秒数）
        this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        const submitParentData = {
          questionId: this.questionId,
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1,
          userAnswer: this.userAnswers,
          isTest: true
        }

        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForEnglish', submitParentData);
        if (response.status === 200) {
          console.log('答题数据提交成功');
          // router.push('/english/exam?year='+this.selectedYear);
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          // router.push('/english/exam?year='+this.selectedYear);
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    },
  }
}
</script>

<style scoped>
.bg-f0f9f9 {
  background-color: #f0f9f9;
  min-height: 100vh;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.passage-container {
  padding: 20px;
  background: white;
  margin: 15px;
  border-radius: 15px;
  line-height: 1.8;
}

.cloze-blank {
  display: inline-block;
  min-width: 60px;
  border-bottom: 2px solid #40e0d0;
  text-align: center;
  margin: 0 5px;
  color: #40e0d0;
}

.options-container {
  margin: 20px 15px;
}

.option-item {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 10px;
  cursor: pointer;
}

.option-item.selected {
  background: #40e0d0;
  color: white;
}

.navigation-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
</style>